// 创建项目Pipeline作业的通用方法
def createPipelineJobsForEnvironment(String configFileName) {
    if (!configFileName) {
        error "configFileName is required."
    }
    
    // 自动拼接resources前缀
    def configText = readFileFromWorkspace("job-dsl_seed-job/resources/${configFileName}")
    println configText
    def config = evaluate(configText)
    def projects = config.projects
    
    projects.each { project ->
        createPipelineJob(project, config)
        println "Created pipeline job: ${project.jobName}"
    }
}

def createPipelineJob(Map project, Map config) {
    pipelineJob(project.jobName) {
        displayName("${project.displayName}")
        description("Automatically generated Pipeline Job for ${project.name}, Jenkinsfile: ${project.scriptPath}")
        parameters {
            // Git 相关参数
            stringParam(
                'BRANCH',
                project.branch ?: 'dev',
                'Git branch to build for ' + project.name
            )
        }
        environmentVariables {
            envs([
                // 从pipeline-jobs.groovy获取的配置
                APP_GIT_URL: project.appGitUrl,
                CREDENTIAL_ID: project.credentialId,
                DEPLOY_APP: project.deployApp,
                DEPLOY_HOST: project.deployHost,
                BUILD_CMD: project.buildCmd,
                BUILD_ARTIFACT: project.buildArtifact,
                DEPLOY_TAGS: project.deployTags ?: '',
                
                // 从构建参数获取的配置
                BRANCH: '${BRANCH}',
            ])
            keepBuildVariables(true)
            keepSystemVariables(true)
        }
        definition {
            cpsScm {
                scm {
                    git {
                        remote {
                            url(config.pipeline.gitUrl)
                            // ✅ 只有当 PipelineCredentialId 非空时才设置
                            if (config.pipeline.credentialId?.trim()) {
                                credentials(config.pipeline.credentialId)
                            }
                        }
                        branch(config.pipeline.branch ?: 'master')
                    }
                }
                scriptPath(project.pipelineScriptPath)
            }
        }
        
        // 设置构建保留策略
        logRotator {
            numToKeep(10)  // 保留最近10次构建
        }
    }
}

// 检查是否有环境参数传入
if (binding.variables.containsKey('configFileName')) {
    // 如果有配置文件参数，为指定文件创建作业
    createPipelineJobsForEnvironment(configFileName)
} else {
    error "No parameter specified. Please provide a configFileName parameter."
}